<!--
  * @Description: 设计界面的文档窗口
 -->
<template>
  <div>
    <el-dialog :title="$t('flyparam.document')" v-bind="$attrs" width="90%" top="5vh" @close="handleClose">
      <div class="flex w-full">
        <el-row class="w-full">
          <el-col :span="6">
            <aside class="sidebar">
              <ul>
                <li v-for="item in contents" :key="item.path">
                  <a class="sidebar-link" :class="{active: item.name === activeName}" @click="() => handleSelectArticle(item.name)">{{ item.title }}</a>
                  <ul v-if="activeName === item.name" class="sidebar-sub-headers">
                    <li v-for="nav in navs" :key="nav.title">
                      <a class="sidebar-link" @click.prevent="() => scrollToTitle(nav.id)">{{ nav.title }}</a>
                    </li>
                  </ul>
                </li>
              </ul>
            </aside>
          </el-col>
          <el-col :span="18">
            <document-content :content="article" :toc="subToc" />
          </el-col>
        </el-row>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { marked } from 'marked'
import axios from 'axios'
import DocumentContent from './article.vue'
const requireAll = (requireContext) => requireContext.keys()

const req = require.context('@document/en', true, /\.md$/)

const fileNames = requireAll(req).map(path => path.replace(/(^\.\/)|(\.md)/g, ''))

console.log(fileNames)

export default {
  components: {
    DocumentContent
  },
  data() {
    return {
      article: '',
      activeName: '',
      navs: [],
      subToc: [],
      index: 0,
      contents: fileNames.map(name => ({ name, title: name }))
    }
  },
  computed: {
    locale() {
      return this.$i18n.locale === 'zh-CN' ? 'zh' : 'en'
    }
  },
  watch: {
    '$i18n.locale': {
      handler() {
        const dir = this.$i18n.locale === 'zh-CN' ? 'zh' : 'en'
        axios
          .get(`/operator/document/${dir}/${this.activeName}.md`)
          .then((data) => {
            this.navs = []
            this.subToc = []
            this.article = marked.parse(data.data)
          })
      }
    }
  },
  mounted() {
    this.initMarked()
    this.handleSelectArticle(this.contents[0].name)
  },
  methods: {
    handleClose() {
      this.$emit('update:model-value', false)
    },

    handleSelectArticle(name) {
      this.activeName = name
      const dir = this.$i18n.locale === 'zh-CN' ? 'zh' : 'en'
      axios
        .get(`/operator/document/${dir}/${name}.md`)
        .then((data) => {
          this.navs = []
          this.subToc = []
          this.article = marked.parse(data.data)
        })
    },
    initMarked() {
      const mdRenderer = new marked.Renderer()
      const that = this
      mdRenderer.heading = function(text, level) {
        const escapedText = text.toLowerCase().replace(/\./g, '')

        if (level >= 1) {
          that.subToc.push({
            id: escapedText,
            level: level,
            label: text
          })
          if (level === 2) {
            that.navs.push({ title: text, level, id: escapedText })
          }
        }

        return `
            <h${level} id="${escapedText}">
              <a name="${escapedText}" class="anchor" href="#${escapedText}">
                <span class="header-link"></span>
              </a>
              ${text}
            </h${level}>`
      }

      mdRenderer.image = function(href, title, text) {
        let target = String(href)
        target = target.replaceAll('\\', '/')
        return `<img src="${import.meta.env.VITE_APP_BASE_API}/resource/images/document/${that.locale}/${target}" alt="${text}"/>`
      }

      marked.use({ renderer: mdRenderer })
    },
    scrollToTitle(id) {
      const el = document.getElementById(id)
      el.scrollIntoView({ behavior: 'smooth' })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

::v-deep .el-dialog__wrapper .el-dialog .el-dialog__body {
  padding: 0;
}

.sidebar {
  padding: 1.5rem 0;
  font-size: 16px;
  background-color: #fff;
  margin: 0;
  top: 60px;
  left: 0;
  height: 85vh;
  bottom: 0;
  box-sizing: border-box;
  border-right: 1px solid #eaecef;
  overflow-y: auto;
  .sidebar-sub-headers {
    padding-left: 1rem;
    font-size: .95em;
    a.sidebar-link {
      border-left: 0.25rem solid transparent;
      padding-top: 0.25rem;
      padding-bottom: 0.25rem;
      border-left: none;
      &.active {
        font-weight: 600;
        border-left-color: $element-blue;
        color: $element-blue;
      }
    }
  }
  .sidebar-link {
    padding-left: 2rem;
  }
  a {
    display: inline-block;
    &.sidebar-link {
      font-size: 1em;
      font-weight: 400;
      display: inline-block;
      color: #2c3e50;
      border-left: 0.25rem solid transparent;
      padding: 0.35rem 1rem 0.35rem 1.25rem;
      line-height: 1.4;
      width: 100%;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      &.active {
        font-weight: 600;
        color: #409eff;
        border-left-color: #409eff;
      }
    }
  }
}

.sub-toc {
  font-size: 14px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial,
    sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji';
  color: #606266;
  padding: 8px;
  cursor: pointer;
}
.sub-toc:hover {
  color: #0969da;
}

.md-sidebar {
  position: sticky;
  width: 320px;
  top: 124px;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: 1;
  padding: 20px;
  padding-left: 10px;
  border-right: 1px solid #d1d5db;
  height: calc(100vh - 65px);
}

.md-subtoc {
  position: sticky;
  min-width: 300px;
  top: 124px;
  overflow-y: hidden;
  overflow-x: hidden;
  z-index: 1;
  padding: 20px 10px 20px 5px;
  border-left: 1px solid #d1d5db;
  height: calc(100vh - 65px);
}
.md-subtoc > .scrollbar,
.md-sidebar > .scrollbar {
  height: calc(100vh - 100px);
}
</style>

<style>
.markdown-body ol {
  list-style: decimal;
}

.markdown-body ul {
  list-style: disc;
}
</style>
